
import React from "react";
import * as THREE from 'three';
import { useAnimate } from "tools/hooks/useAnimate";
import Controller from "../Controller";
import { GLTF } from "../Controller/State/Element";

/** 模拟3维包围盒 Box3 的辅助对象. 和 骨骼 */
export default function useBox3Helper(controller: Controller) {

    /** 选中原件的UUID */
    const selectedElementUuid = controller.useMemo(s => s.selectedElementUuid, []);

    /** 原件字典 */
    const elementMap = controller.useMemo(s => s.elementMap, []);

    /** 选中的原件 */
    const selectedElement = React.useMemo(() => selectedElementUuid && elementMap.get(selectedElementUuid), [elementMap, selectedElementUuid])

    const scene = controller.useMemo(s => s.scene, []);

    const box3Helper = React.useRef<any>();

    const skeletonHelper = React.useRef<any>();

    useAnimate(React.useCallback(() => {
        if (!scene) return;

        scene.remove(skeletonHelper.current);
        scene.remove(box3Helper.current);

        if (!selectedElement || selectedElement.type !== 'gltf') return;

        const box = new THREE.Box3();
        const object3D = selectedElement.object3D as GLTF
        box.setFromObject(object3D.scene.scene);
        box3Helper.current = new THREE.Box3Helper(box);
        scene.add(box3Helper.current);

        skeletonHelper.current = new THREE.SkeletonHelper(object3D.scene.scene);
        scene.add(skeletonHelper.current);

    }, [scene, selectedElement]))
}